package utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * The Class Log creates a log file on which will be stored all the runtime information of the application
 * both on server and client sides. For each one of the sides will have one instance of this class.
 */
public class Log {

	/** The to which will be written the debug information. */
	private FileWriter _file;

	/** The output stream that will be used to write to the file. */
	private BufferedWriter _outputStream;

	/**
	 * Instantiates a new log creating a file with the name of the type side+hh.mm.ss DD-MM-YYYY. For example
	 * for a log file created in the server at the date 04-05-2011 at 19.00.00 the file will have the name
	 * server19.00.00 04-05-2011.txt
	 * 
	 * @param side the side over which the log is being created.
	 */
	public Log(String side){		

		try {
			String filename = side+CurrentDate.getCurrentTime()+".txt";
			File directory = new File("C:\\ProjectoAIAC\\Logs\\");
			if(!directory.exists())
				directory.mkdir();
			
			File file = new File(directory,filename);
			if(!file.exists())
				file.createNewFile();
			_file = new FileWriter(file);
			System.out.println();
		} catch (IOException e) {				
			e.printStackTrace();
		}

		_outputStream = new BufferedWriter(_file);
	}

	/**
	 * This method writes the given string into the log. Before write the string this method prepends the date
	 * ant time of that moment.
	 * 
	 * @param text the string to be written.
	 */
	public synchronized void write(String text){

		synchronized(_outputStream){

			try {
				_outputStream.write(CurrentDate.getCurrentTime()+" "+text);
				_outputStream.newLine();
				_outputStream.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}
